package jp.dodododo.reloadable.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import jp.dodododo.reloadable.util.InitializeUtils;

public class FilterWrapper implements Filter {

	private FilterConfig config;

	private String targetClass;

	private Filter target;

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		target.doFilter(req, res, chain);
	}

	public void init(FilterConfig config) throws ServletException {
		this.config = config;

		targetClass = config.getInitParameter(FilterWrapper.class.getName() + ".targetClass");
		FilterWrapperContainer.register(this);
	}

	public void destroy() {
		FilterWrapperContainer.remove(this);
		config = null;
		targetClass = null;
	}

	public void initTarget() throws Exception {
		ClassLoader cl = Thread.currentThread().getContextClassLoader();
		Class<?> clazz = Class.forName(targetClass, true, cl);
		target = Filter.class.cast(clazz.newInstance());

		long start = System.currentTimeMillis();
		target.init(config);
		long end = System.currentTimeMillis();
		InitializeUtils.initializeInfoLog(targetClass, start, end);
	}

	public void destroyTarget() {
		try {
			if (target != null) {
				target.destroy();
			}
		} finally {
			target = null;
		}
	}
}
